package com.lingxu.base.common.shiro.authc.aop;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.shiro.authc.JwtToken;
import com.lingxu.base.common.shiro.vo.DefConstants;
import com.lingxu.base.common.util.JwtUtil;
import com.lingxu.base.system.oauth2.entity.OAuth2AccessTokenDO;
import com.lingxu.base.system.oauth2.mapper.OAuth2AccessTokenMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description: 鉴权登录拦截器
 * @Author: Scott
 * @Date: 2018/10/7
 **/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

	/**
	 * 执行登录认证
	 *
	 * @param request
	 * @param response
	 * @param mappedValue
	 * @return
	 */
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		return executeLogin(request, response);

		//		try {
//			executeLogin(request, response);
//			return true;
//		} catch (Exception e) {
//			HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
//			httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
//			httpServletResponse.setCharacterEncoding("UTF-8");
//			httpServletResponse.setContentType("application/json; charset=utf-8");
//			try (PrintWriter out = httpServletResponse.getWriter()) {
//				JSONObject jsonObject= (JSONObject) JSONObject.toJSON(Result.error401("Token失效，请重新登录"));
//				out.append(jsonObject.toString());
//			} catch (IOException e2) {
//				e2.printStackTrace();
//			}
//			throw new AuthenticationException("Token失效，请重新登录", e);
//		}
	}

	/**
	 *
	 */
	@Override
	protected boolean executeLogin(ServletRequest request, ServletResponse response)  {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		String token = httpServletRequest.getHeader(DefConstants.X_ACCESS_TOKEN);
		String userName = httpServletRequest.getHeader(DefConstants.X_USER_NAME);
		if (token == null || userName == null) {
			response.setContentType(MediaType.APPLICATION_JSON_VALUE);
			response.setCharacterEncoding("UTF-8");
			try (PrintWriter out = response.getWriter()) {
				JSONObject jsonObject= (JSONObject) JSONObject.toJSON(Result.error401("校验参数缺失"));
				out.append(jsonObject.toString());
			} catch (IOException e2) {
				throw new AuthenticationException("校验参数缺失");
			}
			return false;
        }
		OAuth2AccessTokenMapper oAuth2AccessTokenMapper = SpringUtil.getBean(OAuth2AccessTokenMapper.class);
		OAuth2AccessTokenDO oAuth2AccessTokenDO = oAuth2AccessTokenMapper.selectOne(new LambdaUpdateWrapper<OAuth2AccessTokenDO>()
				.eq(OAuth2AccessTokenDO::getAccessToken, token));
		if (oAuth2AccessTokenDO == null) {
			response.setContentType(MediaType.APPLICATION_JSON_VALUE);
			response.setCharacterEncoding("UTF-8");
			try (PrintWriter out = response.getWriter()) {
				JSONObject jsonObject= (JSONObject) JSONObject.toJSON(Result.error401("Token失效，请重新登录"));
				out.append(jsonObject.toString());
			} catch (IOException e2) {
				throw new AuthenticationException("Token失效，请重新登录");
			}
//			throw new AuthenticationException("Token失效，请重新登录");
			return false;
		}
		token = JwtUtil.sign(userName, userName);

		JwtToken jwtToken = new JwtToken(token);
		// 提交给realm进行登入，如果错误他会抛出异常并被捕获
		getSubject(request, response).login(jwtToken);
		// 如果没有抛出异常则代表登入成功，返回true
		return true;
	}

	/**
	 * 对跨域提供支持
	 */
	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
		httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
		httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
		// 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
		if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
			httpServletResponse.setStatus(HttpStatus.OK.value());
			return false;
		}
		return super.preHandle(request, response);
	}
}
